﻿using Chen.IdentityServer4.DbAll;
using Chen.IdentityServer4.Models;
using CJJ_BlogApiV3.Utils.Tools;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Chen.IdentityServer4.Services
{
    public class AccountService
    {
        private RightDbContext _dbcontext = null;

        public AccountService(RightDbContext dbContext)
        {
            _dbcontext = dbContext;
        }

        public async Task<LoginResult> ValidateUserAsync(string username, string userpwd)
        {
            LoginResult result = new LoginResult() { LoginStatus = UserLoginResult.NoAuth };
            var user = await _dbcontext.SysUsers.AsQueryable().FirstOrDefaultAsync(x => x.LoginNO == username && x.Status == 1);
            if (user == null || user.Id <= 0)
            {
                result.LoginStatus = UserLoginResult.UserNotExist;
                return result;
            }
            if (user.IsLock == 1)
            {
                result.LoginStatus = UserLoginResult.Locked;
                return result;
            }
            //mvc 前端没有对密码加密
            string enypwd = Md5.Encrypt32(userpwd);
            if (!string.Equals(enypwd, user.Password, StringComparison.CurrentCultureIgnoreCase))
            {
                ////更新密码错误逻辑
                //await UpdateErrorNumberAsync(sysuser);

                result.LoginStatus = UserLoginResult.PasswordError;
                return result;
            }

            result.LoginStatus = UserLoginResult.Success;
            result.UserInfo = user;
            return result;
        }


        public async Task<LoginResult> ValidateUserAsync(int uid)
        {
            var query = from ur in _dbcontext.SysuserRoles.AsQueryable()
                        join mu in _dbcontext.ModuleAuthorities on ur.RoleID equals mu.RoleID
                        where ur.SysUserID == uid
                        select ur;
            return null;
        }
    }
}
